# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import *
import tornado.httpclient
from urllib import parse
import d_server

def handle_response(response):
    DEBUG_MSG("tornada test:")
    if response.error:
        ERROR_MSG("Error: %s" % (response.error))
    else:
        INFO_MSG(response.body)

def onTornadoIOLoop(timerID):
    KBEngine.delTimer(timerID)
    tornado.ioloop.IOLoop.current().start()
    KBEngine.addTimer(0.3, 0, onTornadoIOLoop)


class LoginPoller:
    def __init__(self):
        DEBUG_MSG("======================= LoginPoller .__init__ =======================")
        self._callback = None
        self._loginName = ""
        self.datas = ""
        KBEngine.addTimer(0.3, 0, onTornadoIOLoop)

    def getRequest(self):
        pass

    def postRequest(self):
        pass

    def wxLogin(self, loginCode, datas, callBack):
        self._callback = callBack
        self._loginName = loginCode
        self.datas =datas
        #构建微信接口URL: https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        values = {}
        values['appid'] = d_server.AppID
        values['secret'] = d_server.AppSecret
        values['js_code'] = loginCode
        values['grant_type'] = 'authorization_code'
        query_string = parse.urlencode(values)
        url = d_server.Code2SessionUrl + "?" + query_string

        http_client =  tornado.httpclient.AsyncHTTPClient()
        http_client.fetch(url, self.onWxLoginResult)

    def onWxLoginResult(self, response):
        DEBUG_MSG("onWxLoginResult .....")
        if response.error:
            ERROR_MSG("wx Error: %s" % (response.error))
        else:
            INFO_MSG(response.body)
            wxLoginResult = response.body.decode('utf8')
            DEBUG_MSG(wxLoginResult)
            if wxLoginResult:
                userInfo = eval(wxLoginResult)
                if "errcode" not in userInfo:
                    realAccountName = userInfo["openid"]
                    param = eval(self.datas.decode('utf8'))
                    param["session_key"] = userInfo["session_key"]
                    if "unionid" in userInfo:
                        param["unionid"] = userInfo["unionid"]
                    strParam = str(param)
                    DEBUG_MSG("wx login result, loginname: %s" % (self._loginName))
                    self._callback(self._loginName, realAccountName, strParam.encode(), KBEngine.SERVER_ERR_LOCAL_PROCESSING)
